package com.example.houseitemmanagebackend.security;

import com.example.houseitemmanagebackend.utils.JwtUtil;
import io.jsonwebtoken.ExpiredJwtException;
import io.jsonwebtoken.MalformedJwtException;
import io.jsonwebtoken.UnsupportedJwtException;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;

/**
 * JWT认证过滤器
 */
@Slf4j
@Component
public class JwtAuthFilter extends OncePerRequestFilter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private CustomUserDetailsService customUserDetailsService;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {
        try {
            String jwt = parseJwt(request);

            // 仅当有JWT令牌时才进行处理
            if (StringUtils.hasText(jwt)) {
                try {
                    String username = jwtUtil.getUsernameFromToken(jwt);

                    if (username != null && SecurityContextHolder.getContext().getAuthentication() == null) {
                        UserDetails userDetails = customUserDetailsService.loadUserByUsername(username);

                        if (jwtUtil.validateToken(jwt, userDetails)) {
                            UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                                    userDetails, null, userDetails.getAuthorities());

                            authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                            SecurityContextHolder.getContext().setAuthentication(authentication);
                            log.info("已成功验证用户 '{}' 的身份", username);
                        } else {
                            log.warn("用户 '{}' 的令牌验证失败", username);
                        }
                    }
                } catch (ExpiredJwtException e) {
                    log.warn("JWT令牌已过期: {}", e.getMessage());
                } catch (MalformedJwtException e) {
                    log.error("无效的JWT令牌: {}", e.getMessage());
                } catch (UnsupportedJwtException e) {
                    log.error("不支持的JWT令牌: {}", e.getMessage());
                } catch (Exception e) {
                    log.error("无法设置用户认证: {}", e.getMessage());
                }
            } else {
                // 请求没有JWT令牌，这可能是公开的API或者登录/注册请求
                String path = request.getRequestURI();
                if (!path.startsWith("/api/auth/") &&
                        !path.contains("/v3/api-docs") &&
                        !path.contains("/swagger-ui")) {
                    log.debug("访问路径 '{}' 没有JWT令牌", path);
                }
            }
        } catch (Exception e) {
            log.error("认证过滤器发生异常: {}", e.getMessage());
        }

        filterChain.doFilter(request, response);
    }

    /**
     * 从请求头中解析JWT
     */
    private String parseJwt(HttpServletRequest request) {
        String headerAuth = request.getHeader("Authorization");

        if (StringUtils.hasText(headerAuth)) {
            if (headerAuth.startsWith("Bearer ")) {
                return headerAuth.substring(7);
            } else {
                log.warn("Authorization头格式错误，应以'Bearer '开头: {}", headerAuth);
                return null;
            }
        }

        return null;
    }
}